package com.cbwl.eoas.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cbwl.eoas.common.framework.utils.ExceptionUtils;

import sun.misc.BASE64Encoder;

/**
 * Created by yuyunbo on 2017/1/19.
 */
@SuppressWarnings("restriction")
public class Md5Util {

	private static Logger LOG = LoggerFactory.getLogger(Md5Util.class);

	// private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
	// 'f' };
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	protected static final MessageDigest getMessageDigest() throws IllegalArgumentException {
		try {
			return MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			LOG.error(ExceptionUtils.getTrace(e));
			throw new IllegalArgumentException("No such algorithm [MD5]");
		}
	}

	/**  
	*  
	* 加密方法  
	*  
	* rawPass 原始密码  
	*  
	* salt 加密盐  
	**/
	public static String encodePassword(String rawPass, Object salt) {
		String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
		MessageDigest messageDigest = getMessageDigest();
		BASE64Encoder base64en = new BASE64Encoder();
		String digest;
		try {
			digest = base64en.encode(messageDigest.digest(saltedPass.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			LOG.error(ExceptionUtils.getTrace(e));
			throw new IllegalStateException("UTF-8 not supported!");
		}

		return new String(digest);
	}
	
	 // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }
	
	 // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }


	/**  
	*  
	* 加密方法  
	*  
	* rawPass 原始密码  
	**/
	public static String encodePassword(String rawPass) {
		MessageDigest messageDigest = getMessageDigest();
		String digest;
			//digest = messageDigest.digest(rawPass.getBytes("UTF-8"));
			digest = byteToString(messageDigest.digest(rawPass.getBytes()));

		return new String(digest);
	}

	protected static String mergePasswordAndSalt(String password, Object salt, boolean strict) {
		if (password == null) {
			password = "";
		}
		if (strict && (salt != null)) {
			if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
				throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
			}
		}
		if ((salt == null) || "".equals(salt)) {
			return password;
		} else {
			return password + "{" + salt.toString() + "}";
		}
	}

	/* 测试 */
	public static void main(String[] args) {
		//a6xccWveygt7fPs3m2CpeA== Ylj7zeycX9Z/ZIqAgPFLPg==
		System.out.println(Md5Util.encodePassword("123456", "CB00027075"));
		//System.out.println(Md5Util.encodePassword("DXX-MDQ-010-00093(6803cc-").toUpperCase());
	}

}
